package com.kingwang.training.designpattern.memento.bo.text;

import java.util.LinkedList;
import java.util.List;

/**
 * @author King
 */
public class TextMementoTaker {
    private List<TextMemento> undoList = new LinkedList<>();

    private List<TextMemento> redoList = new LinkedList<>();

    public void saveMemento(TextMemento memento) {
        this.undoList.add(memento);
    }

    public TextMemento getUndoMemento() {
        if (this.undoList.isEmpty()) {
            return null;
        }

        return getAndMoveLastElement(this.undoList, this.redoList);
    }

    public TextMemento getRedoMemento() {
        if (this.redoList.isEmpty()) {
            return null;
        }

        return getAndMoveLastElement(this.redoList, this.undoList);
    }

    private TextMemento getAndMoveLastElement(List<TextMemento> source, List<TextMemento> target) {
        int index = source.size() - 1;

        TextMemento result = source.get(index);

        source.remove(index);
        target.add(result);

        return result;
    }
}
